package com.newlink.building.utils

import android.os.CountDownTimer
import java.lang.ref.WeakReference

class Module_Phone_CountdownWorker(
    private val millisInFuture: Long,
    private val countDownInterval: Long = 1000
) {

    private var countdownTimer: CountDownTimer? = null

    //    private var listener: CountdownListener? = null
    private var listenerRef: WeakReference<CountdownListener>? = null

    fun start() {
        countdownTimer = object : CountDownTimer(millisInFuture, countDownInterval) {
            override fun onTick(millisUntilFinished: Long) {
//                listener?.onTick(millisUntilFinished)
                listenerRef?.get()?.onTick(millisUntilFinished)
            }

            override fun onFinish() {
                stop()
//                listener?.onFinish()
                listenerRef?.get()?.onFinish()
            }
        }
        countdownTimer?.start()
    }

    fun stop() {
        countdownTimer?.cancel()
    }

    interface CountdownListener {
        fun onTick(millisUntilFinished: Long)
        fun onFinish()
    }

    fun setListener(listener: CountdownListener) {
//        this.listener = listener
        this.listenerRef = WeakReference(listener)
    }

    fun unRegisterListener() {
        stop()
//        listener = null
        listenerRef?.clear()
        countdownTimer = null
    }
}